package com.koron.css2.newProjectCenter.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.koron.css2.ServerInterface;
import com.koron.css2.baseConfig.mapper.*;
import com.koron.css2.baseConfig.queryBean.BankQueryBean;
import com.koron.css2.baseConfig.queryBean.MeterBoreQueryBean;
import com.koron.css2.baseConfig.queryBean.MeterFactoryQueryBean;
import com.koron.css2.baseConfig.queryBean.MeterModelQueryBean;
import com.koron.css2.baseConfig.vo.BankVO;
import com.koron.css2.baseConfig.vo.MeterBoreVO;
import com.koron.css2.baseConfig.vo.MeterFactoryVO;
import com.koron.css2.baseConfig.vo.MeterModelVO;
import com.koron.css2.clientCenter.bean.AccountInfoBean;
import com.koron.css2.clientCenter.bean.CtmInfoBean;
import com.koron.css2.clientCenter.bean.UserBean;
import com.koron.css2.clientCenter.mapper.AccountInfoMapper;
import com.koron.css2.clientCenter.mapper.CtmInfoMapper;
import com.koron.css2.clientCenter.mapper.UserInfoMapper;
import com.koron.css2.contractmanage.Enum.ContractTypeEnum;
import com.koron.css2.contractmanage.mapper.ContractManageMapper;
import com.koron.css2.contractmanage.querybean.ContractManageQueryBean;
import com.koron.css2.contractmanage.vo.ContractManageVO;
import com.koron.css2.meterService.dto.MsInfoDto;
import com.koron.css2.meterService.mapper.MsInfoMapper;
import com.koron.css2.newProjectCenter.bean.PjMeter;
import com.koron.css2.newProjectCenter.bean.query.PjMeterQuery;
import com.koron.css2.newProjectCenter.mapper.PjMeterMapper;
import com.koron.css2.serviceManage.bean.AdminAreaBean;
import com.koron.css2.serviceManage.bean.BusinessAreaBean;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.mapper.PubAdminAreaMapper;
import com.koron.css2.serviceManage.utils.JsonUtils;
import com.koron.util.Constant;
import com.koron.util.Tools;
import org.apache.commons.lang3.StringUtils;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

public class PjMeterList implements ServerInterface {

    @Override
    public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
        try {
            PjMeterQuery pjMeterQuery = JsonUtils.objectToPojo(req.getData(), PjMeterQuery.class);
            PjMeterMapper pjMeterMapper = factory.getMapper(PjMeterMapper.class);

            List<PjMeter> pjMeterList = pjMeterMapper.getList(pjMeterQuery);
            // 将水表信息转换成前端页面需要的字段信息
            covertMeterInfo(factory, pjMeterList);
            // 9. 返回结果
            MessageBean<List> messageBean = MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "立户列表查询成功", List.class);
            messageBean.setData(pjMeterList);
            return messageBean;
        } catch (Exception e) {
            logger.error("立户列表查询失败", e);
            return MessageBean.create(Constant.MESSAGE_INT_FAIL, "立户列表查询失败:", null);
        }
    }

    public static void covertMeterInfo(SessionFactory factory, List<PjMeter> pjMeterList) throws Exception{
        if (pjMeterList != null && pjMeterList.size() > 0) {
            AccountInfoMapper accountInfoMapper = factory.getMapper(AccountInfoMapper.class);
            CtmInfoMapper ctmInfoMapper = factory.getMapper(CtmInfoMapper.class);
            UserInfoMapper userInfoMapper = factory.getMapper(UserInfoMapper.class);
            MsInfoMapper msInfoMapper = factory.getMapper(MsInfoMapper.class);
            MeterFactoryMapper meterFactoryMapper = factory.getMapper(MeterFactoryMapper.class);
            MeterBoreMapper meterBoreMapper = factory.getMapper(MeterBoreMapper.class);
            MeterModelMapper mapper = factory.getMapper(MeterModelMapper.class);
            PubAdminAreaMapper pubAdminAreaMapper = factory.getMapper(PubAdminAreaMapper.class);
            ContractManageMapper contractManageMapper = factory.getMapper(ContractManageMapper.class);
            BusinessAreaMapper businessAreaMapper = factory.getMapper(BusinessAreaMapper.class);
            BankMapper bankMapper = factory.getMapper(BankMapper.class);
            Map<String, String> contractStatusMap = Tools.mapDicByCode(factory, "CONTRACT_STATUS");

            // 将开户行列表查询出来
            List<BankVO> bankList = bankMapper.findBank(new BankQueryBean());
            // 将临时表账户信息ID 转成集合
            List<String> accountInfoIdList = pjMeterList.stream().map(t -> t.getUserAccountTempId()).collect(Collectors.toList());
            // 将临时表用户信息ID 转成集合
            List<String> userInfoIdList = pjMeterList.stream().map(t -> t.getUserInfoTempId()).collect(Collectors.toList());
            // 将临时表客户信息ID 转成集合
            List<String> ctmInfoIdList = pjMeterList.stream().map(t -> t.getUserCtmTempId()).collect(Collectors.toList());
            // 获取水表ID
            List<String> msInfoIdList = pjMeterList.stream().filter(t -> StringUtils.isNotBlank(t.getMsInfoId())).map(t -> t.getMsInfoId()).collect(Collectors.toList());

            // 获取账户信息
            List<AccountInfoBean> accountInfoList = accountInfoMapper.getListByIdList(accountInfoIdList, AccountInfoBean.ACCOUNTTEMP);
            // 获取用户信息
            List<UserBean> userList = userInfoMapper.selectListByIds(userInfoIdList, UserBean.USERTEMP);
            // 获取客户信息
            List<CtmInfoBean> ctmInfoList = ctmInfoMapper.selectListByIds(ctmInfoIdList, CtmInfoBean.CTMTEMP);
            // 水表信息集合
            List<MsInfoDto> msInfoList = new ArrayList<>();
            if (msInfoIdList.size() > 0){
                msInfoList = msInfoMapper.getMsInfoByIds(msInfoIdList);
            }
            // 水表形态集合
            List<MeterModelVO> modelList = mapper.selectMeterModelList(new MeterModelQueryBean());
            // 水表厂家列表
            List<MeterFactoryVO> meterFactoryList = meterFactoryMapper.selectMeterFactoryList(new MeterFactoryQueryBean());
            // 水表口径列表
            List<MeterBoreVO> meterBoreList = meterBoreMapper.selectMeterBoreList(new MeterBoreQueryBean());

            // 将用户信息里的营业区域ID转成列表集合并过滤空的
            List<String> businessAreaId = userList.stream().filter(t -> StringUtils.isNotBlank(t.getBusinessArea())).map(t -> t.getBusinessArea()).collect(Collectors.toList());
            List<BusinessAreaBean> businessAreaList = new ArrayList<>();
            // 通过营业区域ID查询出营业区域信息
            if (businessAreaId.size() > 0){
                businessAreaList = businessAreaMapper.getBusinessAreaByIds(businessAreaId);
            }

            // 将客户信息里的结构化地址ID转成ID并过滤空的
            List<String> clientAddrIdList = ctmInfoList.stream().filter(t -> StringUtils.isNotBlank(t.getClientAddr())).map(t -> t.getClientAddr()).collect(Collectors.toList());
            List<AdminAreaBean> adminAreaList = new ArrayList<>();
            if (clientAddrIdList.size() > 0){
                // 通过结构化地址ID查询出结构化地址信息
                adminAreaList = pubAdminAreaMapper.selectAdminAreaBeanByIds(clientAddrIdList);
            }

            // 将账户集合转成Map
            Map<String, AccountInfoBean> accountInfoMap = accountInfoList.stream().collect(Collectors.toMap(AccountInfoBean::getId, Function.identity()));
            // 将用户集合转成Map
            Map<String, UserBean> userMap = userList.stream().collect(Collectors.toMap(UserBean::getId, Function.identity()));
            // 将客户集合转成Map
            Map<String, CtmInfoBean> ctmInfoMap = ctmInfoList.stream().collect(Collectors.toMap(CtmInfoBean::getId, Function.identity()));
            // 将水表信息转成Map
            Map<String, MsInfoDto> msInfoMap = msInfoList.stream().collect(Collectors.toMap(MsInfoDto::getId, Function.identity()));
            // 获取区域转成Map
            Map<String, BusinessAreaBean> businessAreaMap = businessAreaList.stream().collect(Collectors.toMap(BusinessAreaBean::getId, Function.identity()));
            // 将结构化地址转成map
            Map<String, AdminAreaBean> adminAreaMap = adminAreaList.stream().collect(Collectors.toMap(AdminAreaBean::getId, Function.identity()));
            // 水表类型
            Map<String, String> meterTypes = Tools.mapDicByCode(factory, "MMT");
            //证件类型
            Map<String, String> cerTypeMap = Tools.mapDicByCode(factory, "IDT");
            // 装表位置
            Map<String, String> setupMeterLocationMap = Tools.mapDicByCode(factory, "CTL");
            Map<String, BankVO> bankMap = bankList.stream().collect(Collectors.toMap(BankVO::getId, Function.identity()));
            for (PjMeter pjMeter : pjMeterList) {
                CtmInfoBean ctmInfoBean = ctmInfoMap.get(pjMeter.getUserCtmTempId());
                CtmInfoBean ctmInfoBeanCopy = ctmInfoBean.clone();
                if (StringUtils.isNotEmpty(ctmInfoBeanCopy.getClientAddr())) {
                    ctmInfoBeanCopy.setClientAddrId(ctmInfoBeanCopy.getClientAddr());
                    AdminAreaBean adminArea = adminAreaMap.get(ctmInfoBeanCopy.getClientAddr());
                    ctmInfoBeanCopy.setClientAddr(adminArea == null ? "" : adminArea.getFullName());
                }
                AccountInfoBean accountInfoBean = accountInfoMap.get(pjMeter.getUserAccountTempId());
                UserBean userBean = userMap.get(pjMeter.getUserInfoTempId());

                // 设置开户银行名称
                if (StringUtils.isNotEmpty(accountInfoBean.getOpenAccountBank())){
                    BankVO bank = bankMap.get(accountInfoBean.getOpenAccountBank());
                    if (bank != null){
                        accountInfoBean.setOpenAccountBankName(bank.getBankName());
                    }
                }

                if (userBean != null && StringUtils.isNotEmpty(userBean.getBusinessArea())) {
                    BusinessAreaBean businessAreaBean = businessAreaMap.get(userBean.getBusinessArea());
                    userBean.setBusinessAreaName(businessAreaBean == null ? "" : businessAreaBean.getAreaName());
                }

                if (userBean != null && StringUtils.isNotEmpty(userBean.getSetupMeterLocation())) {
                    userBean.setSetupMeterLocationName(setupMeterLocationMap.get(userBean.getSetupMeterLocation()));
                }

                if (!StringUtils.isEmpty(userBean.getClientContractAddr())) {
                    userBean.setClientContractAddrId(userBean.getClientContractAddr());
                    String area = pubAdminAreaMapper.selectFullNameById(userBean.getClientContractAddr());
                    userBean.setClientContractAddr(area);
                }

                if (userBean!=null && StringUtils.isNotBlank(userBean.getCertType())){
                    userBean.setCertTypeName(cerTypeMap.get(userBean.getCertType()));
                }

                pjMeter.setUserInfo(userBean);
                String msInfoId = pjMeter.getMsInfoId();
                if (StringUtils.isNotEmpty(msInfoId)) { 
                    MsInfoDto msInfoDto = msInfoMap.get(pjMeter.getMsInfoId());
                    // 水表厂家
                    if (StringUtils.isNotBlank(msInfoDto.getMeterFactory())) {
                        msInfoDto.setMeterFactoryName(meterFactoryList.stream().filter(y -> y.getId().equals(msInfoDto.getMeterFactory())).findFirst().orElse(new MeterFactoryVO()).getFactoryName());
                    }
                    // 水表口径
                    if (StringUtils.isNotBlank(msInfoDto.getMeterBore())) {
                        msInfoDto.setMeterBoreName(meterBoreList.stream().filter(y -> y.getId().equals(msInfoDto.getMeterBore())).findFirst().orElse(new MeterBoreVO()).getBoreName());
                    }
                    //水表形态
                    if (StringUtils.isNotBlank(msInfoDto.getMeterModel())) {
                        msInfoDto.setMeterModelName(modelList.stream().filter(y -> y.getId().equals(msInfoDto.getMeterModel())).findFirst().orElse(new MeterModelVO()).getModelName());
                        if (StringUtils.isBlank(msInfoDto.getMeterModelName())) {
                            msInfoDto.setMeterModelName(msInfoDto.getMeterModel());
                        }
                    }
                    // 水表类型
                    if (StringUtils.isNotBlank(msInfoDto.getMeterType())) {
                        msInfoDto.setMeterTypeName(meterTypes.get(msInfoDto.getMeterType()));
                    }
                    pjMeter.setMsInfo(msInfoDto);
                } else {
                    MsInfoDto msInfoDto = new MsInfoDto();
                    // 水表口径
                    if (StringUtils.isNotBlank(pjMeter.getMeterBore())) {
                        msInfoDto.setMeterBoreName(meterBoreList.stream().filter(y -> y.getId().equals(pjMeter.getMeterBore())).findFirst().orElse(new MeterBoreVO()).getBoreName());
                        msInfoDto.setMeterBore(pjMeter.getMeterBore());
                    }
                    pjMeter.setMsInfo(msInfoDto);
                }

                // 6. 临时客户信息
                pjMeter.setCtmInfo(ctmInfoBeanCopy);

                // 7. 临时账户信息
                pjMeter.setAccountInfo(accountInfoBean);
                //供水合同
                ContractManageQueryBean contractManageQueryBean = new ContractManageQueryBean();
                contractManageQueryBean.setUserNo(userBean.getUserNo());
                contractManageQueryBean.setContractTypes(new String[]{ContractTypeEnum.CONTRACT_TYPE_2.getContractType(),ContractTypeEnum.CONTRACT_TYPE_3.getContractType()});
                ContractManageVO contractManage=new ContractManageVO();
                ContractManageVO gscontractManageVO = contractManageMapper.getContractManage(contractManageQueryBean);
                if (ObjectUtil.isNotNull(gscontractManageVO)){
                    BeanUtil.copyProperties(gscontractManageVO,contractManage);
                }
                // 合同签署状态
                if (StringUtils.isNotEmpty(contractManage.getContractStatus())){
                    contractManage.setContractStatusName(contractStatusMap.get(gscontractManageVO.getContractStatus()));
                }else {
                    // 合同签署状态为空 默认为未签署
                    contractManage.setContractStatusName("未签署");
                }
                pjMeter.setGsContract(contractManage);
            }
        }
    }
}